<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/5/30
 * Time: 20:14
 */

namespace Home\Controller;


use Common\Utils\WeChatUtils;
use Home\Logic\UserLocationLogic;
use Home\Logic\UserLogic;
use Think\Controller;
use Think\Log;

class WeChatMsgController extends Controller
{
    const APPID = 'wx41cc838b916e5f4c';
    const APPSECRET = '4ba4f5005f3bd685a797181b84bbc776';
    const TOKEN = 'gouhuiwan';

    private $utils;

    public function __construct()
    {
        $this->utils = new WeChatUtils(self::APPID, self::APPSECRET, self::TOKEN);
    }

    public function getUtils()
    {
        return $this->utils;
    }

    //接收微信消息
    public function receiveMsg(){
        // 获取请求时POST：XML字符串
        // $_POST,不是key/value型因此不能使用该数组
        $xml_str = $GLOBALS['HTTP_RAW_POST_DATA'];
        #$this->firstVaild();
        // 如果没有post数据，则响应空字符串表示结束
        if (empty($xml_str)) {
            die ('');
        }
        // 解析该xml字符串，利用simpleXML
        libxml_disable_entity_loader(true);//禁止xml实体解析，防止xml注入
        Log::write('Begin','WARN');
        $request_xml = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);//
        // 判断该消息的类型通过元素：MsgType
        switch ($request_xml->MsgType) {
            case 'event': //事件类型
                //判断具体的事件类型（关注，取消，点击）
                $event = $request_xml->Event;
                if('SCAN' == $event){
                    //扫描二维码事件
                    $this->_doQRCode($request_xml);
                    Log::write('扫描二维码事件','WARN');
                }else if('subscribe' == $event){
                    Log::write('EventKey:'.$request_xml->EventKey);
                    $array = explode('_',$request_xml->EventKey);
                    if(count($array) == 2 && !empty($array[1])){
                        $sceneId = $array[1];
                        $this->bindUser($sceneId,$request_xml->FromUserName,$request_xml->ToUserName);
                    }
//                    $this->doSubscribe($request_xml->FromUserName,$request_xml->ToUserName);

                }else if('LOCATION' == $event){
                    $latitude = $request_xml->Latitude;
                    $longitude = $request_xml->Longitude;
                    $openId = $request_xml->FromUserName;
                    $precision = $request_xml->Precision;
                    Log::write('openId:'.$openId);
                    Log::write('$latitude:'.$latitude.'  $longitude:'.$longitude);
                    $logic = new UserLocationLogic();
                    $logic->saveLocation($request_xml->FromUserName,$request_xml->Latitude,$request_xml->Precision,$request_xml->Longitude);
                }else if('CLICK' == $event){
                   $this->utils->msgText($request_xml->FromUserName,$request_xml->ToUserName,'欢迎咨询集品客服，直接回复消息即可咨询') ;
                }
                break;
            case 'text': // 文本消息
                $this->_doText($request_xml);
                break;
        }
    }



    /**
     * 用于第一次验证uURL合法性
     */
    public function firstVaild()
    {
        //检验签名的合法性
        if ($this->_checkSignature()) {
            //签名合法，告知微信公众平台服务器
            echo $_GET['echostr'];
            exit;
        }
    }

    /**
     * 验证签名
     * @return bool
     */
    private function _checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = self::TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * 处理二维码事件推送
     * @param $request_xml 微信事件推送的xml对象
     */
    private function _doQRCode($request_xml){
        $sceneId = $request_xml->EventKey;//推荐人id
        $openId = $request_xml->FromUserName;//openid
        $this->bindUser($sceneId,$openId,$request_xml->ToUserName);
//        $this->utils->msgText($openId,$request_xml->ToUserName,'绑定成功,http://www.jipintc.com/');
    }

    /***
     * 处理文本回复
     * @param $request_xml 微信文本回复的xml对象
     */
    private function _doText($request_xml)
    {
        $key = $request_xml->Content . '';
        $map['keyword'] = array('like','%'.$key.'%');
        $keyword = M('wx_keyword')->where($map)->find();
        if ($keyword && !empty($keyword['reply'])) {
            $this->utils->msgText($request_xml->FromUserName, $request_xml->ToUserName, $keyword['reply']);
        }
    }

    private function bindUser($sceneId,$openId,$ToUserName){
        Log::write('openid:'.$openId,'WARN');
        $logic = new UserLogic();
        $user = $logic->bindSuperior($openId,$sceneId);
        $item['title'] = '欢迎来到集品';
        $item['picurl'] = 'http://'.$_SERVER['HTTP_HOST'].'/Public/images/wechat_bind_bg.jpg';
        $item['url'] = $_SERVER['HTTP_HOST'];
        if($user['first_leader'] == $sceneId){
            //新用户绑定成功
            $item['desc'] ='绑定成功！';
        }else{
            $item['desc'] = '欢迎再次使用！';
        }
        $item_list[0] = $item;
        $this->utils->msgNews($ToUserName,$openId,$item_list);


    }

    public function  test(){

        $this->utils->getNewsList();

    }

    public function doSubscribe($openId,$ToUserName){

        $re = $this->utils->getNewsList();
        $item['title'] = $re->title;
        $item['desc'] = $re->digest;
        $item['picurl']  = $re->thumb_url;
        $item['url'] = $re->url;
        $item_list[0] = $item;
        $this->utils->msgNews($ToUserName,$openId,$item_list);
    }
}